package com.lazycat.backend.service.impl.cart;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lazycat.backend.mapper.GoodMapper;
import com.lazycat.backend.mapper.ShoppingCarMapper;
import com.lazycat.backend.pojo.Good;
import com.lazycat.backend.pojo.UserShoppingCar;
import com.lazycat.backend.service.cart.FetchCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FetchCartServiceImpl implements FetchCartService {

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Override
    public JSONObject fetch(Integer userId) {
        JSONObject resp = new JSONObject();

        QueryWrapper<UserShoppingCar> userShoppingCarQueryWrapper = new QueryWrapper<>();
        userShoppingCarQueryWrapper.eq("user_id", userId);
        List<UserShoppingCar> userShoppingCars = shoppingCarMapper.selectList(userShoppingCarQueryWrapper);
        //BriefItemGood列表
        ArrayList<JSONObject> items = new ArrayList<>();
        for (UserShoppingCar userShoppingCar : userShoppingCars) {
            Integer goodId = userShoppingCar.getGoodId();
            QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
            goodQueryWrapper.eq("id", goodId);
            Good good = goodMapper.selectOne(goodQueryWrapper);
            if (good == null) {
                resp.put("error_message", "no good id " + goodId);
                return resp;
            }

            JSONObject item = new JSONObject();

            item.put("img", good.getGoodImg());
            item.put("name", good.getGoodName());
            item.put("price", good.getGoodPrice());
            item.put("id", good.getId());
            items.add(item);
        }

        resp.put("items", items);
        resp.put("error_message", "success");
        return resp;
    }
}
